﻿using DSBase;
using DSPara;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using TYBase;
using TYControl;
using TYLitedbBase;

namespace DSParaView
{
    public partial class ViewOffset : WindowT
    {
        IUserRole m_userRoleHelper;
        private ViewModelOffset vm = new ViewModelOffset();

        private readonly string section;
        private readonly int chanCount;
        private LiteDB_BaseHelper<Entity_Offset> liteDBHelper;

        /// <summary>
        ///
        /// </summary>
        /// <param name="_section">section 区别多个内阻仪的</param>
        /// <param name="_chanCount">表示多少个通道</param>
        /// <param name="dbName">打标DB的名称,此处最好通过枚举传过来</param>
        public ViewOffset(IUserRole userRoleHelper, string _section, int _chanCount, string dbName)
        {
            liteDBHelper = new LiteDB_BaseHelper<Entity_Offset>(dbName, true);
            InitializeComponent();
            m_userRoleHelper = userRoleHelper;
            vm.ListOffset.Clear();
            for (int i = 0; i < _chanCount; i++)
            {
                vm.ListOffset.Add(new OffsetDataModel { AtChan = i + 1 });
            }
            this.section = _section;
            chanCount = _chanCount;
            this.DataContext = vm;
            this.Loaded += ViewOffset_Loaded;

        }

        private async void ViewOffset_Loaded(object sender, RoutedEventArgs e)
        {

            Entity_Offset listOffsetData = null;
            var ret = await Run(() =>
            {
                try
                {
                    return liteDBHelper.Get(x => x.SectionId == section, out listOffsetData);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ExceptionInfo());
                    return false;
                }
            });
            if (ret == false)
            {
                MessageBox.Show($"获取参数失败,请 删除 运行目录下 {LiteDBHelper.GetFileFullPath(section)}文件,重新配置");
                return;
            }
            if (listOffsetData != null)
                ShowData(listOffsetData);

        }


        void ShowData(Entity_Offset listData)
        {
            for (int i = 0; i < vm.ListOffset.Count; i++)
            {
                vm.ListOffset[i].OCV = 0;
                vm.ListOffset[i].IR = 0;
                vm.ListOffset[i].Current = 0;
            }

            for (int i = 0; i < vm.ListOffset.Count; i++)
            {
                var data = listData.ListOffset.FirstOrDefault(x => x.AtChan == i + 1);
                if (data != null)
                {
                    vm.ListOffset[i].OCV = data.OCV;
                    vm.ListOffset[i].IR = data.IR;
                }
            }

        }
        private Entity_Offset UI2Data()
        {
            Entity_Offset entity_Offset = new Entity_Offset()
            {
                SectionId = section,
            };
            entity_Offset.ListOffset = new List<Entity_Offset_Chan>();
            for (int i = 0; i < vm.ListOffset.Count; i++)
            {
                entity_Offset.ListOffset.Add(new Entity_Offset_Chan
                {
                    AtChan = i + 1,
                    OCV = vm.ListOffset[i].OCV,
                    IR = vm.ListOffset[i].IR,
                });
            }
            return entity_Offset;
        }



        private void BtnClick_Save(object sender, RoutedEventArgs e)
        {
            if (m_userRoleHelper != null)
            {
                if (!m_userRoleHelper.CheckUserLevel(EnumUserLevel.系统管理员 | EnumUserLevel.设备管理))
                {
                    return;
                }
            }

            var data = UI2Data();
            //界面上的保存的数据中
            liteDBHelper.Delete(x => x.SectionId == section);
            liteDBHelper.Insert(data);
            MessageBox.Show("保存OK");
        }

        private void BtnClick_Close(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void BtnClick_Cover(object sender, RoutedEventArgs e)
        {
            if (vm.SelectedOffsetData == null)
            {
                MessageBox.Show("请先选择一行!");
                return;
            }
            for (int i = 0; i < vm.ListOffset.Count; i++)
            {
                if (vm.ListOffset[i] != vm.SelectedOffsetData)
                {
                    vm.ListOffset[i].OCV = vm.SelectedOffsetData.OCV;
                    vm.ListOffset[i].IR = vm.SelectedOffsetData.IR;
                    vm.ListOffset[i].Current = vm.SelectedOffsetData.Current;
                }
            }
        }

        private void BtnClick_ExportXLS_Selected(object sender, RoutedEventArgs e)
        {

            if (vm.ListOffset == null || vm.ListOffset.Count != chanCount)
            {
                MessageBox.Show("未发现规则明细!!");
                return;
            }
            System.Windows.Forms.SaveFileDialog saveDg = new System.Windows.Forms.SaveFileDialog();
            saveDg.Filter = "(*.xlsx)|*.xlsx";
            saveDg.AddExtension = true;
            saveDg.RestoreDirectory = true;
            if (saveDg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //此处做你想做的事
                string fileName = saveDg.FileName;
                if (File.Exists(fileName))
                {
                    MessageBox.Show($"当前目录 存在 文件,请先删除 {fileName}");
                    return;
                }
                List<List<string>> listData = new List<List<string>>();
                for (int i = 0; i < vm.ListOffset.Count; i++)
                {
                    listData.Add(new List<string> {
                        vm.ListOffset[i].AtChan.ToString(),
                        vm.ListOffset[i].OCV.ToString(),
                        vm.ListOffset[i].IR.ToString() ,
                        vm.ListOffset[i].Current.ToString()
                    });
                }
                ExcelHelper.AppendData(fileName, listData);
                MessageBox.Show("保存成功!");
            }
        }



        private void BtnClick_ImportXLS_Single(object sender, RoutedEventArgs e)
        {
            //创建一个打开文件的对话框
            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog()
            {
                Filter = "excel|*.xls",
            };
            //调用ShowDialog()方法显示该对话框，该方法的返回值代表用户是否点击了确定按钮
            if (dialog.ShowDialog() == true)
            {
                string fileName = dialog.FileName;
                List<Entity_Offset_Chan> list = new List<Entity_Offset_Chan>();
                if (ExcelHelper.GetData(fileName, out List<List<string>> listdata))
                {
                    for (int i = 0; i < listdata.Count; i++)
                    {
                        if (listdata[i].Count < 3)
                        {
                            MessageBox.Show($"读取的数据参数数量缺失! {i + 1}");
                            return;
                        }
                        var atChan = listdata[i][0].AsInt();
                        if (atChan <= 0 || atChan > chanCount)
                        {
                            MessageBox.Show($"通道号异常! {i + 1}");
                            return;
                        }
                        var ocv = listdata[i][1].AsDouble();
                        var ir = listdata[i][2].AsDouble();
                        var current = listdata[i][3].AsDouble();
                        if (list.Exists(x => x.AtChan == atChan))
                        {
                            MessageBox.Show($"文件里面通道重复! {i + 1}");
                            return;
                        }
                        list.Add(new Entity_Offset_Chan() { AtChan = atChan, OCV = ocv, IR = ir });
                    }
                    ShowData(new Entity_Offset { ListOffset = list });

                    MessageBox.Show("导入成功!");
                }
            }
        }
    }
}